package com.suxin.test.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/1/14 18:21
 */
@Slf4j
public class EcoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        String bufString = byteBuf.toString(StandardCharsets.UTF_8);
        log.info("accpect server: [" + bufString+"]");
    }

    /**
     * 客户端活跃的时候发送
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("client active...");
        for (int i = 0; i < 100; i++) {
            ctx.channel().writeAndFlush(
                    Unpooled.copiedBuffer(
                            "hello netty".concat(System.getProperty("line.separator"))
                            .getBytes(StandardCharsets.UTF_8)
                    )
            );
        }
    }
}
